import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: login
  },{
    path: '/main',
    name: "main",
    component: () => import ('../views/main.vue'),
    redirect: '/main/student',
    children: [
      {
        path: 'student',
        name: 'student',
        component: () => import ('../views/student.vue'),
      },
      {
        path: 'teacher',
        name: 'teacher',
        component: () => import ('../views/teacher.vue'),
      },
      {
        path: 'helpWang',
        name: 'helpWang',
        component: () => import ('../views/helpWang.vue'),
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 改写push方法 解决push方法跳转导致错误的问题
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  if(typeof(location)=="string"){
    var Separator = "&";
    if(location.indexOf('?')==-1) { Separator='?'; }
    location = location + Separator + "random=" + Math.random();
  }
  return routerPush.call(this, location).catch(error=> error)
}


router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token');
  if(!token) {
    if(to.name == "login") {
      next()
    } else {
      next('/')
    }
  } else {
    next()
  }
})

export default router
